package com.snow.wechat.component;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.*;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.snow.exception.CommonRuntimeException;
import com.snow.wechat.controller.SnowWeXinConfiguration;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Slf4j
@Getter
@Setter
@AllArgsConstructor
@Component
public class WeChatComponent {
    SnowWeXinConfiguration snowWeXinConfiguration;
    StringRedisTemplate stringRedisTemplate;

    public JSONObject jsCode2session(String code) {
        HttpResponse response = HttpUtil.createGet("https://api.weixin.qq.com/sns/jscode2session")
                .form("appid", snowWeXinConfiguration.getAppId())
                .form("secret", snowWeXinConfiguration.getAppSecret())
                .form("js_code", code)
                .form("grant_type", "authorization_code")
                .execute();
        if (response.isOk()) {
            return JSONUtil.parseObj(JSONUtil.parseObj(response.body()));
        }
        log.error("登录失败，访问腾讯服务器失败:{}", response.getStatus());
        throw new CommonRuntimeException("微信登录失败");
    }

    public JSONObject getPhoneNumber(String code) {
        HttpResponse response = HttpUtil.createPost("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + getAccessToken())
                .body(new JSONObject().set("code", code).toString(), ContentType.JSON.getValue())
                .execute();
        if (!response.isOk()) {
            throw new CommonRuntimeException("微信获取手机号失败");
        }
        JSONObject result = JSONUtil.parseObj(response.body());
        if (result.containsKey("errcode") && result.getInt("errcode") != 0) {
            log.error("访问微信获取手机号失败:{}", result);
            throw new CommonRuntimeException("访问微信获取手机号失败");
        }
        return result.getJSONObject("phone_info");
    }


    private String getAccessToken() {
        String accessToken = stringRedisTemplate.opsForValue().get("WeiXinAccessToken");
        if (StrUtil.isNotBlank(accessToken)) {
            return accessToken;
        }
        HttpResponse response = HttpUtil.createGet("https://api.weixin.qq.com/cgi-bin/token")
                .form("grant_type", "client_credential")
                .form("appid", snowWeXinConfiguration.getAppId())
                .form("secret", snowWeXinConfiguration.getAppSecret())
                .execute();

        if (!response.isOk()) {
            throw new CommonRuntimeException("微信登录失败");
        }
        JSONObject result = JSONUtil.parseObj(response.body());
        stringRedisTemplate.opsForValue().set("WeiXinAccessToken", result.getStr("access_token"), 7000, TimeUnit.SECONDS);
        return result.getStr("access_token");
    }
}
